import { IChargeStore, IMpLoginParams, IMpLoginResult } from '@/service/login/login'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useProfileStore = defineStore(
  'profile',
  () => {
    const profileInfo = ref<IMpLoginResult>({
      userinfo: {
        username: '',
        avatar: '',
        chargeStore: [],
      },
      token: '',
    })
    const chargeStore = ref<IChargeStore>({
      notAuditCornerData: null,
      notCommitCornerData: null,
      notPayCornerData: null,
      notRevievrCornerData: null,
      notShipCornerData: null,
      shcornerData: null,
      storeCode: '',
      storeName: '',
      unpayAmount: null,
    })
    const operate = ref<string>('store')
    const mpLoginParams = ref<IMpLoginParams>({
      username: '',
      password: '',
      isDriver: false,
      openid: '',
    })

    const setProfileInfo = (val: IMpLoginResult) => {
      profileInfo.value = val
      if (!chargeStore.value.storeName) {
        const store = profileInfo.value.userinfo.chargeStore
        if (store?.length > 0) {
          setChargeStore(store[0])
        }
      }
    }

    const clearProfileInfo = () => {
      setProfileInfo({
        userinfo: {
          username: '',
          avatar: '',
          chargeStore: [],
        },
        token: '',
      })
      setChargeStore({
        notAuditCornerData: null,
        notCommitCornerData: null,
        notPayCornerData: null,
        notRevievrCornerData: null,
        notShipCornerData: null,
        shcornerData: null,
        storeCode: '',
        storeName: '',
        unpayAmount: null,
      })
      setMpLoginParams({
        username: '',
        password: '',
        isDriver: false,
        openid: '',
      })
    }

    const token = computed(() => profileInfo.value.token)

    const isLogined = computed(() => !!profileInfo.value.token)

    const setChargeStore = (newChargeStore: IChargeStore) => {
      chargeStore.value = newChargeStore
    }

    const setOperate = (newOperate: string) => {
      operate.value = newOperate
    }

    const setMpLoginParams = (newMpLoginParams: IMpLoginParams) => {
      mpLoginParams.value = newMpLoginParams
    }

    return {
      profileInfo,
      setProfileInfo,
      clearProfileInfo,
      token,
      isLogined,
      setChargeStore,
      chargeStore,
      setOperate,
      operate,
      setMpLoginParams,
      mpLoginParams,
    }
  },
  {
    persist: true, // 开启持久化功能
  },
)
